///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2009 Summit Contributors.  
// See: http://code.google.com/p/tyemill/wiki/SummitContributors
//
// The name and logo of Summit are trademarks of TYEMILL, LLC - All Rights 
// Reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a 
// copy of this software and associated documentation files (the "Software"), 
// to deal in the Software without restriction, including without 
// limitation the rights to use, copy, modify, merge, publish, distribute, 
// sublicense, and/or sell copies of the Software, and to permit persons to 
// whom the Software is furnished to do so, subject to the following 
// conditions:
//
// The above copyright notice and this permission notice shall be included 
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
// DEALINGS IN THE SOFTWARE.
///////////////////////////////////////////////////////////////////////////////

package summit.basecamp.helpers
{

import flash.net.URLRequestMethod;

import summit.basecamp.constants.BasecampOperation;
import summit.basecamp.constants.BasecampResource;
import summit.basecamp.constants.MilestoneFilter;
import summit.events.BasecampAPIEvent;
import summit.net.BasecampRequest;
import org.tyemill.utils.Assert;
	
/**
 * Helpers for Basecamp milestone operations.
 */
public class MilestoneHelper
{
	/** @private constants **/
	private static const PATH_HELPER:String = "/milestones/";
	private static const TYPE:String = BasecampResource.MILESTONE;
	private static const FILTER_REQUEST:XML = <request><find/></request>;
	
	/** Empty milestone XML template for use with <code>create</code>. **/
	public static const MILESTONE_TEMPLATE:XML = 
	<request>
		<milestone>
			<title>Add title here</title>
			<project-id/>
			<deadline>08/12/2010</deadline>
			<responsible-party/>
			<notify/>
		</milestone>
	</request>;
	
	/** @private **/	
	public function MilestoneHelper()
	{
	}
	
	/**
	 * Builds a <code>BasecampRequest</code> for marking a milestone as 
	 * complete.
	 * 
	 * @param id The id of the milestone to be marked as complete.
	 * 
	 * @return A request ready for use with <code>BasecampLoader.load</code>.
	 */ 
	public static function complete(id:String):BasecampRequest
	{
		// /milestones/complete/#{id}
		
		SharedOperations.nullEmptyAssert(id, "id");
		
		return new BasecampRequest(PATH_HELPER + "complete/" + id,
		URLRequestMethod.PUT, TYPE, BasecampOperation.COMPLETE);
		
	}
	
	/**
	 * Builds a <code>BasecampRequest</code> for creating a milestone.
	 * 
	 * <p>Typically, the XML provided is based on the template returned from
	 * a call to <code>prepare</code>.</p>
	 * 
	 * <p><code>create</code> on milestone can take up to 10 separate 
	 * milestones as an array. All milestones should be submitted for the
	 * same project.</p>
	 * 
	 * <p><code>title</code> and <code>deadline</code> are required by 
	 * Basecamp. Summit requires <code>project-id</code>.</p>
	 * 
	 * @param content XML representing a milestone.
	 * 
	 * @return A request ready for use with <code>BasecampLoader.load</code>.
	 */   
	public static function create(content:XML):BasecampRequest
	{
		// the difference is in the data of content... 1 vs. many mstones
		// /projects/#{project_id}/milestones/create <- create
		// /projects/#{project_id}/milestones/create <- createBatch
		var projectId:String = content.milestone.child("project-id")[0];
		
		SharedOperations.nullEmptyAssert(projectId, 
		"content did not contain valid project-id", true);
		
		SharedOperations.nullEmptyAssert(content.milestone.child("title")[0],
		"Milestone requires a valid title", true);
		
		SharedOperations.nullEmptyAssert(
		content.milestone.child("deadline")[0], 
		"Milestone requires a valid deadline", true);
		
		return new BasecampRequest(
		"/projects/" + projectId + "/milestones/create", 
		URLRequestMethod.POST, TYPE, BasecampOperation.CREATE, content);
		
	}
	
	/**
	 * Builds a <code>BasecampRequest</code> for deleting a milestone.
	 * 
	 * @param id The id of the milestone to be deleted.
	 * 
	 * @return A request ready for use with <code>BasecampLoader.load</code>.
	 */ 
	public static function destroy(id:String):BasecampRequest
	{
		SharedOperations.nullEmptyAssert(id, "id");
		
		// /milestones/delete/#{id}
		return new BasecampRequest(PATH_HELPER + "delete/" + id,
		URLRequestMethod.DELETE, TYPE, BasecampOperation.DESTROY);
		
	}
	
	/**
	 * Builds a <code>BasecampRequest</code> for getting an existing milestone
	 * from the store.
	 * 
	 * <p>The XML returned is pre-filled with the existing values of 
	 * the identified milestone, and is ready to be resubmitted via the 
	 * <code>update</code> function.</p>
	 * 
	 * @param id The id of the milestone to be retrieved.
	 * @param projectId The id of the project that holds the milestone.
	 * 
	 * @return A request ready for use with <code>BasecampLoader.load</code>.
	 */ 
	public static function edit(id:String, projectId:String):BasecampRequest
	{
		var r:BasecampRequest = read(id, projectId);
		r.operation = BasecampOperation.EDIT;
	//	r.callback = editCallback;
		return r;
	}
	
	/**
	 * Builds a <code>BasecampRequest</code> for reading a list of milestones.
	 * 
	 * <p>By default, all milestones associated with the project specified 
	 * are listed. Providing a filter will scope the list accordingly.
	 * Filter choices are: all, late, completed and upcoming.</p>
	 * 
	 * @param projectId The id of the project from which milestones are to be
	 * listed.
	 * @param filter The filter to reduce the overall scope of the list.
	 * 
	 * @return A request ready for use with <code>BasecampLoader.load</code>.
	 * 
	 * @see summit.basecamp.constants.MilestoneFilter 
	 */ 
	public static function list(projectId:String, 
	filter:String = "all"):BasecampRequest
	{
		SharedOperations.nullEmptyAssert(projectId, "projectId");
		
		var request:XML = null;
		
		if(filter != MilestoneFilter.ALL) //all|late|completed|upcoming
		{ 
			request = new XML(FILTER_REQUEST);
			request.find = filter;
		}
		
		// /projects/#{project_id}/milestones/list
		return new BasecampRequest(
		"/projects/" + projectId + "/milestones/list", URLRequestMethod.GET, 
		TYPE, BasecampOperation.LIST, request);
	}
	
	/**
	 * Builds a <code>BasecampRequest</code> for retrieving a template for a 
	 * new milestone.
	 * 
	 * <p>The template retrieved is used with <code>create</code> to 
	 * submit a new milestone.</p>
	 * 
	 * @param projectId The id of the project that is to be associated
	 * with the milestone when submitted via a call to <code>create</code>.
	 * 
	 * @return A request ready for use with <code>BasecampLoader.load</code>.
	 */ 
	public static function prepare(projectId:String):BasecampRequest
	{
		var x:XML = new XML(MILESTONE_TEMPLATE);
		x.milestone.child("project-id")[0] = projectId;
		
		// loader knows how to handle null ops
		return new BasecampRequest(null, URLRequestMethod.GET, TYPE,
		BasecampOperation.PREPARE, x); 
	}
	
	/**
	 * Builds a <code>BasecampRequest</code> for reading a single milestone.
	 * 
	 * @param id The id of the milestone to be read.
	 * @param projectId The id of the project from which milestones are to be 
	 * read.
	 * 
	 * @return A request ready for use with <code>BasecampLoader.load</code>.
	 */
	public static function read(id:String, projectId:String):BasecampRequest
	{
		var r:BasecampRequest = list(projectId);
		r.operation = BasecampOperation.READ;
		r.callback = readCallback;
		r.summitData = new Object();
		r.summitData.id = id;
		r.summitData.projectId = projectId;
		
		return r;
	}
	
	/**
	 * Builds a <code>BasecampRequest</code> for marking a milestone 
	 * as uncomplete.
	 * 
	 * @param id The id of the milestone to be marked as uncomplete.
	 * 
	 * @return A request ready for use with <code>BasecampLoader.load</code>.
	 */ 
	public static function uncomplete(id:String):BasecampRequest
	{
		// /milestones/uncomplete/#{id}
		
		SharedOperations.nullEmptyAssert(id, "id");
		
		return new BasecampRequest(PATH_HELPER + "uncomplete/" + id,
		URLRequestMethod.PUT, TYPE, BasecampOperation.UNCOMPLETE);
		
	}
	
	/**
	 * Builds a <code>BasecampRequest</code> for updating an existing 
	 * milestone.
	 * 
	 * <p><code>content</code> submitted to <code>update</code> is typically
	 * retrieved from <code>edit</code>.</p>
	 * 
	 * @param content The updated XML content of an existing milestone.
	 * 
	 * @return A request ready for use with <code>BasecampLoader.load</code>. 
	 */ 
	public static function update(content:XML):BasecampRequest
	{
		// Doc says this is a POST - but original branch has this as a PUT...
		// We'll stick with post - but if it fails - you know - try PUT 
		
		//POST /milestones/update/#{id}
		
		var id:String = content.milestone.child("id")[0];
		//delete content.milestone.id;
		
		SharedOperations.nullEmptyAssert(id, 
		"content did not contain valid id", true);	
		
		return new BasecampRequest("/milestones/update/" + id,
		URLRequestMethod.POST, TYPE, BasecampOperation.UPDATE, content);
		
	}
	
	/** @private call for edit operation. **/
	private static function editCallback(e:BasecampAPIEvent):void
	{
		readCallback(e);
		e.loader.data = new XML(e.data.children()[0]);
		e.data = new XML(e.data.children()[0]);
		trace(e.loader.data);
		var i:int = 0;
	}
	
	/** @private callback for read operation - to scope list to requested id
	 */
	private static function readCallback(e:BasecampAPIEvent):void
	{
		var result:XML; //= new XML("<milestones/>");	
		var n:BasecampAPIEvent;
		
		for each(var milestone:XML in e.data.children())
		{
			if(milestone.id == e.loader.basecampRequest.summitData.id)
			{
				result = new XML(milestone);	
			//	result.appendChild(milestone);
				e.data = result;
				e.loader.data = result;
				return;	
			}
		}
		
		Assert.isTrue(false, "Milestone requested could not be found");
	}
	
}
}
//////////////////////////////////////////////////////// gmarius@tyemill.com //